import React, { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Plus, Search, ThumbsDown } from "lucide-react";

import QualityIssueCard from "./QualityIssueCard";
import QualityIssueForm from "./QualityIssueForm";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
export default function QualityIssueManager({
  issues,
  onSave,
  onDelete,
  isLoading,
  onFilteredCountChange,
}) {
  const [showForm, setShowForm] = useState(false);
  const [editingIssue, setEditingIssue] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [filterCategory, setFilterCategory] = useState("all");

  const handleEdit = (issue) => {
    setEditingIssue(issue);
    setShowForm(true);
   setTimeout(() => {
        const formElement = document.getElementById("quality-issue-form");
        if (formElement) {
          formElement.scrollIntoView({ behavior: "smooth", block: "start" });
        }
      }, 250);
  };

  const handleCancel = () => {
    setEditingIssue(null);
    setShowForm(false);
  };

  const handleSubmit = async (data) => {
    await onSave(editingIssue ? { ...data, id: editingIssue.id } : data);
    handleCancel();
  };

  // 使用useMemo缓存过滤结果，避免每次渲染都创建新数组
  const filteredIssues = useMemo(() => {
    return issues.filter((issue) => {
      const termMatch =
        searchTerm === "" ||
        issue.issueName.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (issue.category &&
          issue.category.toLowerCase().includes(searchTerm.toLowerCase()));
      const categoryMatch =
        filterCategory === "all" || issue.category === filterCategory;
      return termMatch && categoryMatch;
    });
  }, [issues, searchTerm, filterCategory]); // 只有依赖项变化时才重新计算

  // 使用useCallback记忆化回调函数（如果在组件内部定义的话）
  // 但这里回调来自props，应该在父组件中使用useCallback处理

  useEffect(() => {
    if (onFilteredCountChange) {
      // 添加防抖动或检查值是否真的变化
      onFilteredCountChange(filteredIssues.length);
    }
  }, [filteredIssues.length, onFilteredCountChange]);

  // 缓存分类列表
  const categories = useMemo(() => {
    return [...new Set(issues.map((i) => i.category).filter(Boolean))];
  }, [issues]);

  return (
    <div className="space-y-6">
      <div className="flex flex-col md:flex-row gap-4">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 w-4 h-4" />
          <Input
            placeholder="搜索通病名称或分类..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="pl-10"
          />
        </div>

        <Select value={filterCategory} onValueChange={setFilterCategory}>
          <SelectTrigger className="w-full md:w-[180px]">
            <SelectValue placeholder="所有类别" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">所有类别</SelectItem>
            {categories.map((cat) => (
              <SelectItem key={cat} value={cat}>
                {cat}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        <Button
          onClick={() => {
            setEditingIssue(null);
            setShowForm(true);
          }}
          className="bg-red-600 hover:bg-red-700"
        >
          <Plus className="w-4 h-4 mr-2" />
          新建质量通病
        </Button>
      </div>

      {showForm && (
        <QualityIssueForm
          issue={editingIssue}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}

      {isLoading ? (
        <div className="text-center p-8">加载中...</div>
      ) : filteredIssues.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredIssues.map((issue) => (
            <QualityIssueCard
              key={issue.id}
              issue={issue}
              onEdit={handleEdit}
              onDelete={onDelete}
            />
          ))}
        </div>
      ) : (
        <div className="text-center py-12 text-gray-500 bg-white rounded-lg shadow-sm border border-gray-200">
          <ThumbsDown className="w-12 h-12 mx-auto mb-4 text-gray-300" />
          <p className="text-lg font-medium mb-2">暂无匹配的质量通病条目</p>
          <p>尝试调整搜索条件或创建新的条目</p>
        </div>
      )}
    </div>
  );
}
